package com.xci.edu.module.foreground.pc.train.core;

import com.github.lvyanyang.annotation.AllowAnonymous;
import com.xci.edu.core.service.TrainStudentService;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class StudentrHandlerInterceptor implements HandlerInterceptor {
    @Resource
    private TrainStudentService trainStudentService;

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //region 匿名访问验证
        Method method = ((HandlerMethod) handler).getMethod();
        //权限检测,确认使用者是否有权限访问此功能 类/方法上有@AllowAnonymous,允许匿名登录,直接放行
        if (IsAllowAnonymous(method)) {
            return true;
        }
        //endregion

        if(trainStudentService.getCurrentStudent()==null){
            response.sendRedirect("/train/login");//跳转到登录页面
            return false;
        }
        return true;
    }

    /**
     * 检测方法是否属于匿名方法
     * @param method 方法对象
     */
    private boolean IsAllowAnonymous(Method method) {
        if (method.getAnnotation(AllowAnonymous.class) != null) {
            return true;
        }
        return false;
    }
}